/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.CertTypeEnum;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.CustomCheckParamUtil;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.dto.OrgInfoResultDto;
import com.icinfo.cloud.provider.peripheralinterface.xzzf.service.IXzzfInterfaceService;
import com.icinfo.cloud.provider.punish.api.dto.*;
import com.icinfo.cloud.provider.punish.api.enums.*;
import com.icinfo.cloud.provider.punish.api.service.ICaseTransferApiService;
import com.icinfo.cloud.provider.punish.common.electricsent.dto.DocumentSendPageRequest;
import com.icinfo.cloud.provider.punish.config.mapper.SysAreaMapper;
import com.icinfo.cloud.provider.punish.config.mapper.SysDepartParamMapper;
import com.icinfo.cloud.provider.punish.config.model.SysArea;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CasePartiesRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainDetailAuxiliaryInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainDetailInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseHandlePersonRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainDetailAuxiliaryInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainDetailInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseHandlePersonRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseReasonMainRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseReasonMainRecordVo;
import com.icinfo.cloud.provider.punish.ucase.criminaltransfer.service.ICaseCriminalTransferFileService;
import com.icinfo.cloud.provider.punish.ucase.punishinform.vo.CaseCriminalTransferFileVo;
import com.icinfo.cloud.provider.punish.usersign.mapper.MemberUserSignMapper;
import com.icinfo.cloud.xzcf.provider.member.org.model.MemberOrg;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 描述:  case_payment_main_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年03月01日
 */
@Service
@Slf4j
public class CaseTransferApiServiceImpl extends MyBatisServiceSupport implements ICaseTransferApiService {

    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICaseHandlePersonRecordService caseHandlePersonRecordService;
    @Resource
    private ICaseReasonMainRecordService caseReasonMainRecordService;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private SysDepartParamMapper sysDepartParamMapper;
    @Resource
    private SysAreaMapper sysAreaMapper;
    @Resource
    private ICaseCriminalTransferFileService caseCriminalTransferFileService;
    @Resource
    private IXzzfInterfaceService xzzfInterfaceService;
    @Resource
    private MemberUserSignMapper memberUserSignMapper;

    /**
     * 描述： 查询移送案件详情
     *
     * @return {@link CaseBaseInfoResponse}
     * @author: zhengqiang
     * @date: 2022/9/28
     * @param: caseId
     **/
    @Override
    public CaseBaseInfoResponse getTransferCaseBaseDetail(String caseId) {
        CaseBaseInfoResponse response = new CaseBaseInfoResponse();
        response.setCaseBaseId(caseId);
        //封装案件信息
        buildCaseInfo(response);
        //封装当事人信息
        buildPartiesInfo(response);
        //涉案财物信息
        buildFinanceInfo(response);
        //证据材料
        buildDocumentRecord(response);
        return response;
    }

    /**
     * 封装案件信息
     *
     * @param response
     */
    private void buildCaseInfo(CaseBaseInfoResponse response) {
        String caseId = response.getCaseBaseId();
        //案件信息封装
        CaseMainInfo main = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (ObjectUtils.isEmpty(main)) {
            throw new BusinessException("案件信息不存在！");
        }
        response.setHandDeptCode(main.getCaseOrgCode());
        response.setHandDeptName(main.getCaseOrgName());

        CaseMainDetailInfo detail = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
        //response.setXzdwajbh(main.getCaseNumber());
        //修改为用caseId,案件编号会重复,涉刑移送会失败
        response.setXzdwajbh(caseId);
        //行政案件类别映射
        response.setAjlb(TransferCaseTypeEnum.getGaCodeByCfCode(main.getCaseType()));
        //案件来源映射
        response.setAjly(TransferCaseSourceEnum.getGaCodeByCfCode(detail.getCaseSourceId()));
        //执法部门处理
        Example orgExample = new Example(SysDepartParam.class);
        orgExample.createCriteria().andEqualTo("orgCode", main.getCaseOrgCode());
        List<SysDepartParam> sysDepartParams = sysDepartParamMapper.selectByExample(orgExample);
        if (ObjectUtils.isEmpty(sysDepartParams)) {
            throw new BusinessException("单位参数配置信息为空！");
        }
        SysDepartParam sysDepartParam = sysDepartParams.get(0);
        //调用执法平台接口获取机构信息
        /*OrgInfoResultDto orgInfoResultDto = xzzfInterfaceService.getOrgInfoByUnicode(sysDepartParam.getUnicode());
        if (ObjectUtils.isEmpty(orgInfoResultDto) || ObjectUtils.isEmpty(orgInfoResultDto.getAreaCode())) {
            throw new BusinessException("查询部门信息失败！");
        }
        String areaCode = orgInfoResultDto.getAreaCode();
        */
        //修改为查询处罚member_org表
        List<MemberOrg> memberOrgList = memberUserSignMapper.selectMemberOrg(main.getCaseOrgCode());
        if (ObjectUtils.isEmpty(memberOrgList)) {
            throw new BusinessException("查询部门信息失败！");
        }
        MemberOrg memberOrg = memberOrgList.get(0);
        if (!memberOrg.getUniCode().equals(sysDepartParam.getUnicode())) {
            throw new BusinessException("部门的统一社会信用代码配置不一致!处罚系统为:" + sysDepartParam.getUnicode()
                    + "),执法平台为:" + memberOrg.getUniCode());
        }
        response.setZfbmbs(memberOrg.getAreaCode() + "-" + sysDepartParam.getUnicode());//区域-统一社会信用代码
        response.setZfbmmc(sysDepartParam.getOrgStandardName());//机构名称
        //案件名称
        response.setXzcfajmc(main.getCaseName());
        //案件来源日期
        response.setAjlyrq(DateUtil.localDateTimeToDate(main.getCaseRegistTime()));
        response.setSxwfss(detail.getCaseConciseCondition());
        //涉案金额及违法所得处理
        //String punishKinds = detail.getPunishKinds();
        String draftPunishMoney = detail.getDraftPunishMoney();
        String confiscateIllegalMoney = detail.getConfiscateIllegalMoney();
        //分别处罚时: 处罚种类,处罚金额及没收违法所得金额处理
        if (HandleTypeEnum.PART_PUNISH.getCode().equals(main.getHandleType())) {
            Example auxiliaryExample = new Example(CaseMainDetailAuxiliaryInfo.class);
            auxiliaryExample.createCriteria().andEqualTo("caseId", caseId);
            List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfos = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryExample);
            if (!ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfos)) {
                //处罚种类
                //Set<String> kindSet = new HashSet<>();
                //处罚金额
                BigDecimal punishMoney = new BigDecimal("0");
                //没收违法所得
                BigDecimal illegalMoney = new BigDecimal("0");
                for (CaseMainDetailAuxiliaryInfo auxiliaryInfo : caseMainDetailAuxiliaryInfos) {
                    /*if (!ObjectUtils.isEmpty(auxiliaryInfo.getPunishKinds())) {
                        String[] split = auxiliaryInfo.getPunishKinds().split(",");
                        Collections.addAll(kindSet, split);
                    }*/
                    //处罚金额处理
                    if (!ObjectUtils.isEmpty(auxiliaryInfo.getDraftPunishMoney())) {
                        try {
                            BigDecimal money = new BigDecimal(auxiliaryInfo.getDraftPunishMoney());
                            punishMoney = punishMoney.add(money);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    //没收违法所得处理
                    if (!ObjectUtils.isEmpty(auxiliaryInfo.getConfiscateIllegalMoney())) {
                        try {
                            BigDecimal money = new BigDecimal(auxiliaryInfo.getConfiscateIllegalMoney());
                            illegalMoney = illegalMoney.add(money);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                //punishKinds = kindSet.stream().collect(Collectors.joining(","));
                draftPunishMoney = punishMoney.toString();
                confiscateIllegalMoney = illegalMoney.toString();
            }
        }
        if (!ObjectUtils.isEmpty(draftPunishMoney)) {
            response.setSaje(draftPunishMoney);
        }
        if (!ObjectUtils.isEmpty(confiscateIllegalMoney)) {
            response.setWfsd(confiscateIllegalMoney);
        }

        //案发地址
        response.setFadd(detail.getCaseHappenAddressDetail());

        //案发时间
        response.setFasj(DateUtil.localDateTimeToDate(detail.getCaseHappenTime()));
        //执法人员姓名
        List<CaseHandlePersonRecord> personList = caseHandlePersonRecordService.getCaseHandlePersonRecordList(caseId);
        String handPerson = personList.stream().map(e -> e.getHandlePersonName()).collect(Collectors.joining(","));
        response.setZfryxm(handPerson);
        //刑事案由
        response.setAy(detail.getCriminalCaseReason());
        //案件所属领域
        List<CaseReasonMainRecordVo> caseReasonMainRecordList = caseReasonMainRecordService.getCaseReasonRecordListByCaseId(caseId);
        if (!ObjectUtils.isEmpty(caseReasonMainRecordList)) {
            response.setAjssly(caseReasonMainRecordList.get(0).getTerritoryCode());
        }
        //案件移送信息 通过后才会有移送书文号
        List<CaseDocumentRecordDto> caseDocumentRecordList = caseDocumentRecordMapper.selectCaseDocumentRecordListByKindCode(caseId, DocumentKindEnum.DOC_KIND_DK2SXFZAJYSS.getCode());
        if (!ObjectUtils.isEmpty(caseDocumentRecordList)) {
            //throw new BusinessException("移送信息不存在！");
            //移送书文号
            response.setYsswh(caseDocumentRecordList.get(0).getDocumentNumber());
        }

        personList.forEach(e -> {
            if (HandlePersonTypeEnum.MAIN.getCode().equals(e.getHandlePersonType())) {
                response.setYsr(e.getHandlePersonName());
                response.setLxfs(e.getHandleOrgTel());
            }
        });
        //送往单位
        response.setSwdw(detail.getCriminalCaseTransferDeptCode());

    }

    /**
     * 封装当事人信息数据
     *
     * @param response
     */
    private void buildPartiesInfo(CaseBaseInfoResponse response) {
        String caseId = response.getCaseBaseId();
        //人员列表
        List<PersonInfoDto> personInfoDtoList = new ArrayList<>();
        //单位列表
        List<UnitInfoDto> unitInfoDtoList = new ArrayList<>();
        CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto(caseId, null, YesOrNoEnum.NO.getCode());
        List<CasePartiesInfoVo> casePartiesInfoList = casePartiesRecordService.getCasePartiesInfoList(queryDto);
        if (!ObjectUtils.isEmpty(casePartiesInfoList)) {
            casePartiesInfoList.forEach(e -> {
                if (PartyTypeEnum.PERSON.getCode().equals(e.getPartyType())) {
                    //1.人员信息
                    PersonInfoDto personInfoDto = new PersonInfoDto();
                    personInfoDto.setId(e.getId());
                    personInfoDto.setCaseBaseId(caseId);
                    personInfoDto.setXm(e.getPartyName());
                    //证件类型映射处理
                    String gaCode = TransferCertTypeEnum.getGaCodeByCfCode(e.getPartyIdentityTypeCode());
                    if (!ObjectUtils.isEmpty(gaCode)) {
                        personInfoDto.setZjlx(gaCode);
                        personInfoDto.setZjhm(e.getPartyIdentityCode());
                        personInfoDto.setCertTypeMes(TransferCertTypeEnum.getGaValueByCfCode(e.getPartyIdentityTypeCode()));
                    }
                    //性别映射处理
                    personInfoDto.setXb(TransferSexEnum.getCodeByDes(e.getSex()));
                    //出生日期处理
                    if (!ObjectUtils.isEmpty(e.getBirth())) {
                        try {
                            Date birth = DateUtils.parseDate(e.getBirth(), "yyyy年MM月dd日");
                            personInfoDto.setCsrq(birth);
                        } catch (Exception exception) {
                        }
                    }
                    //年龄处理
                    try {
                        personInfoDto.setNl(Integer.valueOf(e.getAge()));
                    } catch (Exception exception) {
                    }

                    if (ObjectUtils.isEmpty(personInfoDto.getNl()) && CertTypeEnum.SFZ.getCode().equals(e.getPartyIdentityType())) {
                        Map birAgeSex = BaseUtil.getBirAgeSex(e.getPartyIdentityCode());
                        if (ObjectUtils.isEmpty(birAgeSex.get("age"))) {
                            personInfoDto.setNl(Integer.valueOf(birAgeSex.get("age").toString()));
                        }
                    }

                    //现住地代码处理
                    String areaCodes = getAreaCodeByNames(e.getAddressAreasStr());
                    if (!ObjectUtils.isEmpty(areaCodes)) {
                        personInfoDto.setXzdAreaCode(areaCodes);
                        personInfoDto.setAreaCodeMes(e.getAddressAreasStr().replace(",", ""));
                        //底级区划码
                        String[] areaCodeArr = areaCodes.split(",");
                        personInfoDto.setXzd(areaCodeArr[areaCodeArr.length-1]);
                    }
                    personInfoDto.setXzdxz(e.getAddressDetail());
                    personInfoDto.setLxdh(e.getContactPhone());
                    personInfoDto.setIsNeedToAdd(YesOrNoEnum.YES.getCode());
                    personInfoDtoList.add(personInfoDto);
                } else {
                    //2.单位信息
                    UnitInfoDto unitInfoDto = new UnitInfoDto();
                    unitInfoDto.setId(e.getId());
                    unitInfoDto.setCaseBaseId(caseId);
                    unitInfoDto.setDwmc(e.getPartyName());
                    unitInfoDto.setZcdd(e.getAddress());
                    unitInfoDto.setTyshxydm(e.getPartyIdentityCode());
                    unitInfoDto.setFddbrxm(e.getLegalName());
                    //证件类型映射
                    String gaCode = TransferCertTypeEnum.getGaCodeByCfCode(e.getLegalCertType());
                    if (!ObjectUtils.isEmpty(gaCode)) {
                        unitInfoDto.setFddbrzjlx(gaCode);
                        unitInfoDto.setFddbrzjhm(e.getLegalCertNo());
                        unitInfoDto.setCertTypeMes(TransferCertTypeEnum.getGaValueByCfCode(e.getLegalCertType()));
                    }
                    unitInfoDto.setXgzrrlxfs(e.getContactPhone());
                    unitInfoDto.setIsNeedToAdd(YesOrNoEnum.YES.getCode());
                    if (CustomCheckParamUtil.doCheckAllParamIsNotEmpty(unitInfoDto)) { //校验参数是否全部不为空
                        unitInfoDto.setIsNeedToAdd(YesOrNoEnum.NO.getCode());
                    }
                    unitInfoDtoList.add(unitInfoDto);
                }
            });

            response.setPersonInfoDtoList(personInfoDtoList);
            response.setUnitInfoDtoList(unitInfoDtoList);
        }
    }

    /**
     * 证据材料封装
     *
     * @param response
     */
    private void buildDocumentRecord(CaseBaseInfoResponse response) {
        String caseId = response.getCaseBaseId();
        List<EvidenceInfoDto> evidenceInfoDtoList = new ArrayList<>();
        //涉嫌犯罪案件移送书(案件移送函)
        List<CaseDocumentRecordDto> ajyshList = caseDocumentRecordMapper.selectCaseDocumentRecordListByKindCode(caseId, DocumentKindEnum.DOC_KIND_DK2SXFZAJYSS.getCode());
        if (!ObjectUtils.isEmpty(ajyshList)) {
            //throw new BusinessException("案件移送函不存在！");
            EvidenceInfoDto anyshDto = new EvidenceInfoDto();
            anyshDto.setBusinessType(Constant.STRING_1);
            anyshDto.setEvidenceType(TransferEvidenceTypeEnum.AJYSH.getCode());
            anyshDto.setEvidenceTypeMes(TransferEvidenceTypeEnum.AJYSH.getDes());
            anyshDto.setEvidenceFileType(TransferEvidenceFileTypeEnum.PICTURE.getCode());
            List<FileInfoDto> fileInfoDtoList = new ArrayList<>();
            ajyshList.forEach(e -> {
                anyshDto.setCreateUserId(e.getCreateUserId());
                anyshDto.setCreateUserName(e.getCreateUserName());
                FileInfoDto fileInfoDto = new FileInfoDto();
                fileInfoDto.setFileName(TransferEvidenceTypeEnum.AJYSH.getDes());
                fileInfoDto.setFileUrl(!ObjectUtils.isEmpty(e.getDocumentUrlAfterSeal()) ? e.getDocumentUrlAfterSeal() : e.getDocumentUrl());
                fileInfoDto.setFileType("pdf");
                fileInfoDto.setCreateTime(DateUtil.localDateTimeToDate(e.getDocumentCreateTime()));
                fileInfoDtoList.add(fileInfoDto);
            });
            anyshDto.setFileInfoDtoList(fileInfoDtoList);
            evidenceInfoDtoList.add(anyshDto);
        }


        //案件调查报告
        /*List<CaseDocumentRecordDto> zjbgList = caseDocumentRecordMapper.selectCaseDocumentRecordListByKindCode(caseId, DocumentKindEnum.DOC_KIND_ZJBG.getCode());
        if (ObjectUtils.isEmpty(zjbgList)) {
            throw new BusinessException("案件调查报告不存在！");
        }
        EvidenceInfoDto zjbgDto = new EvidenceInfoDto();
        zjbgDto.setBusinessType(Constant.STRING_1);
        zjbgDto.setEvidenceType(TransferEvidenceTypeEnum.ZJBG.getCode());
        zjbgDto.setEvidenceTypeMes(TransferEvidenceTypeEnum.ZJBG.getDes());
        zjbgDto.setEvidenceFileType(TransferEvidenceFileTypeEnum.PICTURE.getCode());
        List<FileInfoDto> zjbgDtoList = new ArrayList<>();
        zjbgList.forEach(e -> {
            zjbgDto.setCreateUserId(e.getCreateUserId());
            zjbgDto.setCreateUserName(e.getCreateUserName());
            FileInfoDto fileInfoDto = new FileInfoDto();
            fileInfoDto.setFileName(TransferEvidenceTypeEnum.ZJBG.getDes());
            fileInfoDto.setFileUrl(!ObjectUtils.isEmpty(e.getDocumentUrlAfterSeal()) ? e.getDocumentUrlAfterSeal() : e.getDocumentUrl());
            fileInfoDto.setFileType("pdf");
            fileInfoDto.setCreateTime(DateUtil.localDateTimeToDate(e.getDocumentCreateTime()));
            zjbgDtoList.add(fileInfoDto);
        });
        zjbgDto.setFileInfoDtoList(zjbgDtoList);
        evidenceInfoDtoList.add(zjbgDto);*/
        dealTransferFile(evidenceInfoDtoList,caseId);
        response.setEvidenceInfoDtoList(evidenceInfoDtoList);

    }

    /**
     * 描述：添加选择的移送文件
     *
     * @param evidenceInfoDtoList dto证据信息列表
     * @author shishengyao
     * @date 2022/10/11
     */
    private void dealTransferFile(List<EvidenceInfoDto> evidenceInfoDtoList, String caseId) {
        List<CaseCriminalTransferFileVo> fileList = caseCriminalTransferFileService.getCaseCriminalTransferFileListByCaseId(caseId);
        for (CaseCriminalTransferFileVo fileVo : fileList) {
            EvidenceInfoDto transferFileDto = new EvidenceInfoDto();
            transferFileDto.setBusinessType(Constant.STRING_1);
            transferFileDto.setEvidenceType(fileVo.getEvidenceType());
            transferFileDto.setEvidenceTypeMes(fileVo.getEvidenceTypeName());
            //transferFileDto.setEvidenceFileType(fileVo.getFileType());
            //都是pdf 先定死图片类型
            transferFileDto.setEvidenceFileType(TransferEvidenceFileTypeEnum.PICTURE.getCode());
            List<FileInfoDto> transferFileList = new ArrayList<>();
            transferFileDto.setCreateUserId(fileVo.getUploadUserId());
            transferFileDto.setCreateUserName(fileVo.getUploadUserName());
            FileInfoDto fileInfoDto = new FileInfoDto();
            fileInfoDto.setFileName(fileVo.getFileName());
            fileInfoDto.setFileUrl(fileVo.getFileUrl());
            fileInfoDto.setFileType("pdf");
            fileInfoDto.setCreateTime(DateUtil.localDateTimeToDate(fileVo.getUploadTime()));
            transferFileList.add(fileInfoDto);
            transferFileDto.setFileInfoDtoList(transferFileList);
            evidenceInfoDtoList.add(transferFileDto);
        }

    }

    /**
     * 根据多级区域名称获取多级区划码(以逗号分隔)
     *
     * @param areas 多个区域名称以逗号分隔
     * @return
     */
    private String getAreaCodeByNames(String areas) {
        if (ObjectUtils.isEmpty(areas)) {
            return null;
        }
        List<String> areaCodeList = new ArrayList<>();
        String[] areaArr = areas.split(",");
        for (int i = 0; i < areaArr.length; i++) {
            String areaName = areaArr[i];
            Example areaExample = new Example(SysArea.class);
            Example.Criteria criteria = areaExample.createCriteria();
            criteria.andEqualTo("isDel", Constant.STRING_0).andEqualTo("areaName", areaName);
            List<SysArea> areaList = sysAreaMapper.selectByExample(areaExample);
            if (ObjectUtils.isEmpty(areaList)) {
                return null;
            }
            areaCodeList.add(areaList.get(0).getAreaCode());
        }
        return areaCodeList.stream().collect(Collectors.joining(","));
    }

    /**
     * 涉案财物信息封装
     *
     * @param response
     */
    private void buildFinanceInfo(CaseBaseInfoResponse response) {
        String caseId = response.getCaseBaseId();
        List<FinanceInfoDto> financeInfoDtoList = new ArrayList<>();
        //查封（扣押）决定书
        List<CaseDocumentRecordDto> ajyshList = caseDocumentRecordMapper.selectCaseDocumentRecordListByKindCode(caseId, DocumentKindEnum.DOC_KIND_DK2CFKYJDS.getCode());
        if (ObjectUtils.isEmpty(ajyshList)) {
            return;
        }
        CaseDocumentRecordDto caseDocumentRecordDto = ajyshList.get(0);
        String documentContent = caseDocumentRecordDto.getDocumentContent();
        JSONObject docJson = JSON.parseObject(documentContent);
        JSONArray attachmentList = docJson.getJSONArray("attachmentList");
        if (ObjectUtils.isEmpty(attachmentList)) {
            return;
        }
        for (int i = 0; i < attachmentList.size(); i++) {
            JSONObject o = (JSONObject) attachmentList.get(i);
            FinanceInfoDto financeInfoDto = new FinanceInfoDto();
            //移送案件财务标识
            financeInfoDto.setCwbh(caseDocumentRecordDto.getId() + i);
            //物品名称
            financeInfoDto.setWpmc(o.getString("name"));
            //数量
            financeInfoDto.setSl(o.getString("quantity"));
            //单位
            financeInfoDto.setDw(o.getString("specification"));
            //备注
            financeInfoDto.setTz(ObjectUtils.isEmpty(o.getString("tableRemark")) ? "无" : o.getString("tableRemark"));
            //财物分类
            financeInfoDto.setCwfl("物品");
            //持有人
            financeInfoDto.setCyr(docJson.getString("mainHandlePerson"));
            //存放地
            financeInfoDto.setCfd(docJson.getString("putAddress"));
            //行政强制措施类型
            financeInfoDto.setXzqzcslx("扣押");
            financeInfoDtoList.add(financeInfoDto);
        }
        response.setFinanceInfoDtoList(financeInfoDtoList);
    }

    /**
     * 描述： 办案协同-统一两法衔接查询-我的移送
     *
     * @author: yehuafei
     * @date: 2022/11/29
     **/
    @Override
    public List<CaseTransferPageResponse> getCaseTransferList(CaseTransferPageRequest request) {
        checkOrgCode(request);
        PageHelper.startPage(request.getPageNum(),request.getLength());
        List<CaseTransferPageResponse> list = caseMainInfoMapper.selectCaseTransferList(request);
        List<LawEnDic> lawEnDicList = caseMainInfoMapper.getCaseTransferDicByType("XSAY");
        list.forEach(e -> {
            e.setCaseStatus(LawCaseStageEnum.getValueByCode(e.getCaseStatus()));
            e.setAy(this.setAyName(e.getAy(),lawEnDicList));
        });
        return list;
    }

    /**
     * 案件移送设置案源中文
     * @param ayCodes
     * @param lawEnDicList
     * @return
     */
    private String setAyName(String ayCodes, List<LawEnDic> lawEnDicList){
        if (StringUtils.isBlank(ayCodes)){
            return "";
        }
        String[] ayArray = ayCodes.split(Constant.STRING_COMMA);
        List<String> ayList = new ArrayList<>();
        for (String ay : ayArray) {
            List<LawEnDic> collect = lawEnDicList.stream().filter(dic -> dic.getDicCode().equals(ay)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect) && collect.size() > 0){
                ayList.add(collect.get(0).getDicName());
            }
        }
        return StringUtils.join(ayList,Constant.STRING_COMMA);
    }

    /**
     * orgCode处理
     *
     * @param queryDto
     * @return void
     * @author lxj
     * @date 2022/3/31
     **/
    private void checkOrgCode(CaseTransferPageRequest queryDto) {
        queryDto.setOrg(0);
        if (StringUtils.isEmpty(queryDto.getOrgCode())) {
            return;
        }
        List<String> orgCodeList = new ArrayList<>();
        List<String> deptCodeList = new ArrayList<>();
        String[] str = queryDto.getOrgCode().split(",");

        for (String s : str) {
            if(s.indexOf("_")>0){
                orgCodeList.add(s);
            }else {
                deptCodeList.add(s);
            }
        }
        if(orgCodeList.size()>0&&deptCodeList.size()>0){
            queryDto.setOrg(1);
        }else if(orgCodeList.size()>0){
            queryDto.setOrg(2);
        }else if(deptCodeList.size()>0){
            queryDto.setOrg(3);
        }

        queryDto.setOrgCodeList(orgCodeList);
        queryDto.setDeptCodeList(deptCodeList);
    }

    /***
     * 描述： 获取审批后的移送书及移送文号
     *
     * @author: zhengqiang
     * @date: 2023/1/12
     * @param: caseId
     * @return {@link CaseBaseInfoResponse}
     **/
    @Override
    public CaseBaseInfoResponse getTransferDetailAfterApproval(String caseId) {
        CaseBaseInfoResponse response = new CaseBaseInfoResponse();
        response.setCaseBaseId(caseId);
        //涉嫌犯罪案件移送书(案件移送函)
        List<CaseDocumentRecordDto> ajyshList = caseDocumentRecordMapper.selectCaseDocumentRecordListByKindCode(caseId, DocumentKindEnum.DOC_KIND_DK2SXFZAJYSS.getCode());
        if (ObjectUtils.isEmpty(ajyshList)) {
            throw new BusinessException("案件移送函不存在！");
        }
        //设置移送书文号
        response.setYsswh(ajyshList.get(0).getDocumentNumber());

        //设置移送证据--案件移送函
        List<EvidenceInfoDto> evidenceInfoDtoList = new ArrayList<>();
        EvidenceInfoDto anyshDto = new EvidenceInfoDto();
        anyshDto.setBusinessType(Constant.STRING_1);
        anyshDto.setEvidenceType(TransferEvidenceTypeEnum.AJYSH.getCode());
        anyshDto.setEvidenceTypeMes(TransferEvidenceTypeEnum.AJYSH.getDes());
        anyshDto.setEvidenceFileType(TransferEvidenceFileTypeEnum.PICTURE.getCode());
        List<FileInfoDto> fileInfoDtoList = new ArrayList<>();
        ajyshList.forEach(e -> {
            anyshDto.setCreateUserId(e.getCreateUserId());
            anyshDto.setCreateUserName(e.getCreateUserName());
            FileInfoDto fileInfoDto = new FileInfoDto();
            fileInfoDto.setFileName(TransferEvidenceTypeEnum.AJYSH.getDes());
            fileInfoDto.setFileUrl(!ObjectUtils.isEmpty(e.getDocumentUrlAfterSeal()) ? e.getDocumentUrlAfterSeal() : e.getDocumentUrl());
            fileInfoDto.setFileType("pdf");
            fileInfoDto.setCreateTime(DateUtil.localDateTimeToDate(e.getDocumentCreateTime()));
            fileInfoDtoList.add(fileInfoDto);
        });
        anyshDto.setFileInfoDtoList(fileInfoDtoList);
        evidenceInfoDtoList.add(anyshDto);

        response.setEvidenceInfoDtoList(evidenceInfoDtoList);
        return response;
    }
}
